import React, { useEffect, useState } from 'react';
import { Menu } from 'antd';
import { useMatches, useNavigate } from 'react-router-dom';
import MyIcon from '../MyIcon';
import './index.scss'

function getItem(label, key, icon, children) {
  return {
    label,
    key,
    icon,
    children
  };
}

const items = [
  getItem('后台首页', '/home', <MyIcon font='icon-home' />),
  getItem('账号管理', '/account1', <MyIcon font='icon-account' />, [
    getItem('账号列表', '/account'),
    getItem('个人中心', '/account/center'),
    getItem('添加账号', '/account/add'),
    getItem('修改密码', '/account/update'),
  ]),
  getItem('商品管理', '/commodity1', <MyIcon font='icon-commodity' />, [
    getItem('商品列表', '/commodity'),
    getItem('商品添加', '/commodity/add'),
    getItem('商品分类', '/commodity/classify'),
  ]),
  getItem('订单管理', '/orders', <MyIcon font='icon-order' />),
  getItem('店铺管理', '/shop', <MyIcon font='icon-shop' />),
  getItem('销售统计', '/sale1', <MyIcon font='icon-sale' />, [
    getItem('商品统计', '/sale'),
    getItem('订单统计', '/sale/orders'),
  ]),
];

const getLevelKeys = (items1) => {
  const key = {};
  const func = (items2, level = 1) => {
    items2.forEach((item) => {
      if (item.key) {
        key[item.key] = level;
      }
      if (item.children) {
        return func(item.children, level + 1);
      }
    });
  };
  func(items1);
  return key;
};

const levelKeys = getLevelKeys(items);

const LeftMenu = () => {

  const [openKey, setOpenKey] = useState(['/home'])
  const [selectKey, setSelectKey] = useState(['/home'])

  const navigate = useNavigate()
  const matches = useMatches()

  const toPath = (e) => {
    navigate(e.key)
  }


  const openChange = (e) => {
    setOpenKey(e.slice(-1))
  };


  useEffect(() => {
    setOpenKey([matches[0].data.key])

    setSelectKey(matches[matches.length - 1].data.key)
  }, [matches])


  return (
    <div className='left'>
      <div className="title">
        <span>外卖平台</span>
      </div>
      <Menu
        mode="inline"

        onOpenChange={openChange}  // 菜单列表
        openKeys={openKey}  // 打开的菜单列表
        selectedKeys={selectKey}  // 选中菜单
        onClick={toPath}

        style={{
          width: 200
        }}
        theme='dark'
        items={items}
      />
    </div>
  );
};
export default LeftMenu;